package com.android.locationapi.maps;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;


public class serv extends Service{

	static String sessionusername;
	
	@Override
	public void onStart(Intent intent,int startid)
	
	 {
		// TODO Auto-generated method stub
		
		
		Bundle extras= intent.getExtras();
		
		
		
		String usrnm = extras.getString("strusername");
		String pass = extras.getString("strpass");
		

		
		
		 Log.v("username", usrnm);
	        Log.v("strpasswd", pass);
	        
	        if ((usrnm.equals("")) || (pass.equals("")))
	        {
	        	Toast.makeText(this,"Error!!! :: Both the username and password field should be entered.", 6000).show();
	        }
	        else
	        {
					
					//bish : call the function to connect to the server and validate the user 
				    try
				    {
				    	
				    	
				    	
				    	  String result = "";
				          //the year data to send
				          ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				          nameValuePairs.add(new BasicNameValuePair("username",usrnm));
				          nameValuePairs.add(new BasicNameValuePair("password",pass));
				          InputStream is = null;
				           
				          //http post
				          try{
				                  HttpClient httpclient = new DefaultHttpClient();
				                  HttpPost httppost = new HttpPost(serveripaddress.servipaddr+"login.php");
				                  httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				                  Log.v("Server", "Here now");
				                  HttpResponse response = httpclient.execute(httppost);
				                  Log.v("Server", "Waiting for response!!!");
				                  HttpEntity entity = response.getEntity();
				                  Log.v("Server", "In here now");
				                  is = entity.getContent();
				                  Log.v("Bishon: Returned from the server 0 : ", is.toString());
				          }catch(Exception e){
				                  Log.v("log_tag", "Error in http connection "+e.toString());
				          }
				          //convert response to string
				          try{
				                  BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
				                  StringBuilder sb = new StringBuilder();
				                  String line = null;
				                  while ((line = reader.readLine()) != null) {
				                          sb.append(line);
				                  }
				                  is.close();
				           
				                  result=sb.toString();
				                  Log.v("Bishon: Returned from the server : ", result);
				                  
				                  
				          	}
				          catch(Exception e){
				                  Log.v("log_tag", "Error converting result "+e.toString());
				          	}
				           
				  
							
							if (result.equals("LOGIN_SUCCESS"))
							{
								Log.v("Server", "Authenticated In here now");
								Log.v("bish in serv","done 1");
								sessionusername = usrnm; //to be used for the whole session
								Intent locationSendingIntent = new Intent(serv.this, NewService.class);
					            startService(locationSendingIntent);
					            Intent explicitIntent2 = new Intent(serv.this,ShowMap.class);
								explicitIntent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								Log.v("Server", "After start run");
					    		startActivity(explicitIntent2);
					    		Log.v("in serv","done  2");  
					    		
							}
							else if (result.equals("INCORRECT_PASSWORD"))
							{
								Intent explicitIntent3 = new Intent(serv.this,notauthenticated.class);
								explicitIntent3.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					    		startActivity(explicitIntent3);
					    		Log.v("bish NOT in serv","NOT done 1");
					    		
							} else if (result.equals("DOES_NOT_EXIST")) 
							{
								Intent explicitIntent4 = new Intent(serv.this,Register.class);
								explicitIntent4.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					    		startActivity(explicitIntent4);
					    		Log.v("bish NOT in serv","NOT done 1");																
							}								
							}
					
				    
				    catch (Exception e) {
						// TODO: handle exception
				    	Log.v("Bishon launch error", e.toString());
				    	System.out.println("error"+e.toString());
					}
	        }
		
		/*Log.v("username",usrnm);
		Log.v("in serv","done");*/
		
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
     
	
}
